<template>
  <div class="user">
    <div class="addUser">
      <el-button type='primary'
                 @click="userVisible=true,state=0,form['role']=groupData[0].rname">增加用户</el-button>
    </div>
    <template>
      <el-table :data="userData"
                style="width: 100%">
        <el-table-column prop="uname"
                         label="用户账号"
                         align="center">
        </el-table-column>
        <el-table-column prop="phone"
                         label="用户电话"
                         align="center">
        </el-table-column>
        <el-table-column prop="role"
                         min-width="150px"
                         align="center"
                         label="用户所属管理组">
        </el-table-column>
        <el-table-column align="center"
                         width="200px"
                         label="操作">
          <template slot-scope="scope">
            <el-button type="primary"
                       size="small"
                       @click="state=1,userVisible=true,edit(scope.row)">编辑</el-button>
            <el-button type="danger"
                       size="small"
                       @click="removeUser(scope.row.uid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template>
      <el-dialog :title="state ? '修改用户' : '添加用户'"
                 v-el-drag-dialog
                 :visible.sync="userVisible"
                 width="40%"
                 @closed="Object.keys(form).forEach(key => form[key] = '')"
                 center>
        <div class="form">
          <el-form ref="form"
                   :model="form"
                   label-width="100px">
            <el-form-item label="用户名:">
              <el-input v-model="form.uname"
                        placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="手机号:">
              <el-input v-model="form.phone"
                        placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="选择管理组:">
              <el-radio-group v-model="form.role">
                <el-radio v-for='item of groupData'
                          @change='GetRoleID(item)'
                          :key='item.id'
                          :label="item.rname">
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="userVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="state ? UpdateUser() : AddUser()">{{state ? '修改' : '添加'}}</el-button>
        </span>
      </el-dialog>
    </template>
  </div>
</template>

<script>

import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
export default {
  name: 'user',
  directives: { elDragDialog },
  data () {
    return {
      userData: [],
      groupData: [],
      state: '',
      userVisible: false, //对话框状态 false 隐藏  true 显示
      form: {
        uname: '',
        phone: '',
        role: '',
        uid: ''
      },
    }
  },

  methods: {
    async init () {  //获取用户列表
      try {
        const [user, group] = await Promise.all([this.api.userList(), this.api.groupList()])
        this.userData = user.data.list
        this.groupData = group.data
      } catch (err) {
        throw (err)
      }
    },
    async AddUser () {  //添加用户
      try {
        /**
         * @param  uname 用户名
         * @param  phone 手机号
         * @param  role  管理组名称
         * @param  role_id 管理组id
         */
        let role_id = this.groupData[this.groupData.findIndex((v) => this.form['role'] === v.rname)].rid
        const res = await this.api.addUser(Object.assign({}, { ...this.form, role_id: role_id }))
        if (res.code == 1) {
          this.$message({ message: res.msg, type: 'success' })
          this.userVisible = false
          this.init()
        } else {
          this.$message.error(res.msg)
        }
      } catch (err) {
        throw (err)
      }
    },
    edit (row) {
      this.form = Object.assign({}, row)
      if (row.role === '超级管理员') {
        this.$message({ message: '此项为超级管理员', type: 'info' })
      }
    },
    async UpdateUser () {  //修改用户信息
      try {
        /**
      * @param  uname   用户名
      * @param  phone   手机号
      * @param  role    管理组名称
      * @param  role_id 管理组id
      * @param  uid     用户id
      */
        let role_id = this.groupData[this.groupData.findIndex((v) => this.form['role'] === v.rname)].rid
        const res = await this.api.updateUser(Object.assign({}, { ...this.form, role_id: role_id }))
        if (res.code == 1) {
          this.$message({ message: res.msg, type: 'success' })
          this.userVisible = false
          this.init()
        } else {
          this.$message.error(res.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * @param uid 用户id,根据用户id删除
     */
    removeUser (uid) {
      this.$confirm('此操作将永久删除改用户, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(async () => {
          const res = await this.api.delUser({ uid: uid })
          if (res.code == 1) {
            this.$message({ message: res.msg, type: 'success' })
            this.init()
          } else {
            this.$message.error(res.msg)
          }
        }).catch(() => { });
    },

  },
  mounted () {
    this.init()
  }
}
</script>

<style scoped rel="stylesheet/scss" lang="scss">
.addUser {
  text-align: right;
  padding: 15px 10px;
  background-color: white;
  margin: 10px 0;
}
</style>

